import os
import time
import cv2
import numpy as np
from airtest.core.api import *
from PIL import Image


# 加载模板图片
def load_templates():
    templates = {}
    for number in range(1,12):
        path = os.path.join(TEMPLATE_DIR, "2048activity", str(number)+".png")
        # print(path)
        # 读取灰度图
        template = cv2.imread(path)
        templates[2**number] = template
        # cv2.imshow('oxxostudio', template)  # 使用名為 oxxostudio 的視窗開啟圖片
        # cv2.waitKey(0)  # 按下任意鍵停止
        # cv2.destroyAllWindows()
    return templates


# 获取棋盘截图
def get_board_image():
    # 使用 Airtest 截图
    image_path = "snapshots/board.png"
    snapshot(filename=image_path)

    # 裁剪棋盘区域
    img = cv2.imread(image_path)
    board_area = img[BOARD_Y1:BOARD_Y2, BOARD_X1:BOARD_X2]
    return board_area


# 分割棋盘格子
def split_board(board_image):
    cell_width = board_image.shape[1] // 4
    cell_height = board_image.shape[0] // 4
    cells = []
    for row in range(4):
        for col in range(4):
            x1 = col * cell_width
            y1 = row * cell_height
            x2 = x1 + cell_width
            y2 = y1 + cell_height
            cell = board_image[y1:y2, x1:x2]
            cells.append(cell)
    return cells


# 识别数字
def recognize_number(cell_image, templates):
    best_match = None
    best_score = 0
    for number, temp in templates.items():
        result = cv2.matchTemplate(cell_image, temp, cv2.TM_CCOEFF_NORMED)
        _, score, _, _ = cv2.minMaxLoc(result)
        if score > best_score and score > 0.8:
            best_match = number
            best_score = score
    return best_match if best_score > 0.8 else 0



# 构建棋盘状态
def build_board(cells, templates):
    board = [[0] * 4 for _ in range(4)]
    for i, cell in enumerate(cells):
        number = recognize_number(cell, templates)
        board[i // 4][i % 4] = number
    return board



# 计算评分（示例：最大值 + 空格数 * 10）
def calculate_score(board):
    max_value = max(max(row) for row in board)
    empty_cells = sum(row.count(0) for row in board)
    return max_value + empty_cells * 10


#
#
# 模拟滑动（需根据实际棋盘中心点调整坐标）
def swipe_direction(direction):
    center_x = (BOARD_X1 + BOARD_X2) // 2
    center_y = (BOARD_Y1 + BOARD_Y2) // 2
    if direction == "UP":
        swipe(center_x, center_y + 100, center_x, center_y - 100)
    elif direction == "DOWN":
        swipe(center_x, center_y - 100, center_x, center_y + 100)
    elif direction == "LEFT":
        swipe(center_x + 100, center_y, center_x - 100, center_y)
    elif direction == "RIGHT":
        swipe(center_x - 100, center_y, center_x + 100, center_y)


# 自动化主流程
def main():
    templates = load_templates()
    # while True:
    board_img = get_board_image()
    cells = split_board(board_img)
    board = build_board(cells, templates)
    score = calculate_score(board)
    print(f"当前评分: {score}, 棋盘状态: {board}")

    # 这里替换为你的决策逻辑（示例：随机滑动）
    directions = ["UP", "DOWN", "LEFT", "RIGHT"]
    # swipe_direction(np.random.choice(directions))

    # time.sleep(1)  # 控制操作频率


if __name__ == "__main__":
    # 图片资源目录
    TEMPLATE_DIR = "D:\dev\PycharmProjects\castle_clash_helper\\templates"

    # 棋盘区域坐标（需根据实际屏幕调整）
    BOARD_X1, BOARD_Y1 = 425, 120
    BOARD_X2, BOARD_Y2 = 1170, 860
    # 连接设备（需提前启动 Airtest IDE 或配置 ADB）
    GAME_PACKAGE_NAME = 'com.igg.castleclash_tw'
    SNAPSHOT_DIRECTORY = './snapshots'

    # 連接設備
    init_device("Android")
    main()
